<?php

namespace App\Models\OpenShop\InvestmentPromotion;

use App\Enums\OpenShop\InvestmentPromotion\ErrCode;
use App\Enums\OpenShop\InvestmentPromotion\SignOrderEnum;
use App\Exceptions\Custom\CustomHttpResponseException;
use App\Models\BaseModel;
use App\Models\Traits\KfSoftDeletes;
use DateTimeInterface;
use Illuminate\Database\Eloquent\Relations\HasMany;

class OpenShopSpaceDesignCostMappingModel extends BaseModel
{
    use KfSoftDeletes;
    protected $table = 'open_shop_space_design_cost_mapping';

    public const BASE_DESIGN_AREA     = 30;
    public const BASE_OVER_DESIGN_FEE = 100;

    protected $fillable = [
        'orderNo',
        'preparationNo',
        'designFee',
        'merchantFee',
        'overDesignFee',
        'totalDesign',
        'storeArea',
        'designArea',
        'baseDesignArea',
        'overDesignArea',
        'isDeleted',
        'createdAt',
        'createdByUid',
        'updatedAt',
        'updatedAtByUid',
        'orderStatus',
        'payStatus',
        'payTime',
        'totalFee',
    ];

    protected $appends = [
        'orderStatusText',
        'payStatusText',
        'payTimeText'
    ];

    protected function serializeDate(DateTimeInterface $date)
    {
        return $date->format("Y-m-d H:i:s");
    }


    const ORDER_STATUS_0 = 0;
    const ORDER_STATUS_1 = 1;
    const ORDER_STATUS_2 = 2;
    const ORDER_STATUS_3 = 3;

    const CN_ORDER_STATUS = [
        self::ORDER_STATUS_0 => '已生成',
        self::ORDER_STATUS_1 => '进行中',
        self::ORDER_STATUS_2 => '已完成',
        self::ORDER_STATUS_3 => '已关闭',
    ];

    const ORDER_PAY_STATUS_0 = 0;
    const ORDER_PAY_STATUS_1 = 1;
    const ORDER_PAY_STATUS_2 = 2;
    const ORDER_PAY_STATUS_3 = 3;
    const ORDER_PAY_STATUS_4 = 4;

    const CN_PAY_STATUS = [
        self::ORDER_PAY_STATUS_0 => '未付款',
        self::ORDER_PAY_STATUS_1 => '部分支付',
        self::ORDER_PAY_STATUS_2 => '已支付',
        self::ORDER_PAY_STATUS_3 => '部分退款',
        self::ORDER_PAY_STATUS_4 => '全额退款',
    ];

    public function getPayStatusTextAttribute()
    {
        return self::CN_PAY_STATUS[$this->payStatus];
    }

    public function getOrderStatusTextAttribute()
    {
        return self::CN_ORDER_STATUS[$this->orderStatus];
    }

    public function getPayTimeTextAttribute()
    {
        return $this->payTime != 0 ? date('Y-m-d H:i:s', $this->payTime) : '';
    }

    public function signOrderRel()
    {
        return $this->hasOne(OpenShopSignOrderModel::class, 'orderNo', 'orderNo');
    }

    /**
     * @return HasMany
     */
    public function payHistoryRel(): HasMany
    {
        return $this->hasMany(OpenShopSignOrderPayHistoryModel::class, "orderNo", "orderNo");
    }

    /**
     * 单笔支付成功
     * @param int $payPrice
     * @return $this
     */
    public function onePaySuccess(int $payPrice): self
    {
        // 已支付金额累加
        $this->payFee += $payPrice;

        if ($this->payFee == $this->totalFee) {

            // 整单支付完成
            $this->payStatus   = self::ORDER_PAY_STATUS_2;
            $this->orderStatus = self::ORDER_STATUS_1;
            $this->payTime     = time();
        } elseif ($this->payFee < $this->totalFee) {

            // 部分支付完成
            $this->payStatus = self::ORDER_PAY_STATUS_1;
        } else {

            // 支付金额超过应付
            throw new CustomHttpResponseException(
                ErrCode::errCodeTrans(ErrCode::CODE_PAY_PRICE_OVERFLOW)
            );
        }

        $this->save();

        return $this;
    }

    /**
     * 待支付的设计单数量
     * @param string $orderNo
     * @return int
     */
    public static function waitPayCount(string $orderNo): int
    {
        return OpenShopSpaceDesignCostMappingModel
            ::query()
            ->where('orderNo', $orderNo)
            ->whereIn('payStatus', [
                OpenShopSpaceDesignCostMappingModel::ORDER_PAY_STATUS_0,
                OpenShopSpaceDesignCostMappingModel::ORDER_PAY_STATUS_1
            ])
            ->whereIn('orderStatus', [
                OpenShopSpaceDesignCostMappingModel::ORDER_STATUS_0,
                OpenShopSpaceDesignCostMappingModel::ORDER_STATUS_1
            ])
            ->count();
    }
}
